package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.comman.Transactions;
import com.yuntongxun.ecdemo.voicechat.listeners.IRecyclerViewItemListener;
import com.yuntongxun.ecdemo.voicechat.listeners.LoadMoreClickListener;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadView;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadViewImpl;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.ui.adapter.TransactionsAdapter;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.NetUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.ExStaggeredGridLayoutManager;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderSpanSizeLookup;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.OnRecyclerViewScrollListener;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.RecyclerViewUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;

/**
 *支付记录列表
 */
public class TransactionsActivity extends BaseChatActivity implements ICommonViewUi, IRecyclerViewItemListener, LoadMoreClickListener, SwipeRefreshLayout.OnRefreshListener{

    @InjectView(R.id.swipe_refresh_layout)
    public SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.recycler_view)
    public RecyclerView recyclerView;

    private HeaderAndFooterRecyclerViewAdapter adapter;
    private ExStaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<Transactions> mResultList = new ArrayList<Transactions>();

    private ICommonRequestPresenter iCommonRequestPresenter = null;

    private ILoadView iLoadView = null;

    private View loadMoreView = null;

    private boolean isRequesting = false;//标记，是否正在刷新

    private int mCurrentPage = 0;

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_transactions;
    }

    @Override
    protected void initViewsAndEvents() {

        setTitle("Transactions");

        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);

        iLoadView = new ILoadViewImpl(mContext, this);

        loadMoreView = iLoadView.inflate();

        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new MyScrollListener());

        refreshListView();

        //第一次进来时刷新
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        swipeRefreshLayout.setRefreshing(true);

                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }
    }

    /**
     * 解析结果
     *
     * @param result
     * @return
     */
    public List<Transactions> parseResult(String result) {
//        数据解析
        try {
            JsonHelper<Transactions> dataParser = new JsonHelper<Transactions>(
                    Transactions.class);
            return dataParser.getDatas(
                    result, "list");
        }catch (Exception ex){
            return new ArrayList<Transactions>();
        }

    }

    @Override
    public void toRequest(int eventTag) {

        if(eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT){
            //刷新

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            mCurrentPage = 1;

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "100");

            iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.ACCOUNT_AMOUNT_DETAIL, map);

        }else if(eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT){
            //加载更多

            if (isRequesting)
                return;

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                iLoadView.showErrorView(loadMoreView);
                return;
            }

            if (mResultList.size() < ApiConstants.Request.PAGE_NUMBER) {
                return;
            }

            mCurrentPage++;

            iLoadView.showLoadingView(loadMoreView);

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "100");

            iCommonRequestPresenter.request(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT, mContext, ApiConstants.Urls.ACCOUNT_AMOUNT_DETAIL, map);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {

        if(eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT){
            //下拉刷新

            List<Transactions> resultList = parseResult(result);

            mResultList.clear();
            mResultList.addAll(resultList);

            refreshListView();

        }else if(eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT){
            //加载更多

            List<Transactions> resultList = parseResult(result);

            mResultList.addAll(resultList);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {

        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {

        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        isRequesting = status;

        if (!status) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    public void clickLoadMoreData() {
        toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
    }

    @Override
    public void onItemClick(int position) {
        Toast.makeText(mContext, "onItemClick>" + position, Toast.LENGTH_SHORT).show();
    }

    public void refreshListView() {

        TransactionsAdapter mIntermediary = new TransactionsAdapter(mContext, mResultList, this);

        adapter = new HeaderAndFooterRecyclerViewAdapter(mIntermediary);

        recyclerView.setAdapter(adapter);

        if (mResultList.size() >= ApiConstants.Request.PAGE_NUMBER) {

            RecyclerViewUtils.setFooterView(recyclerView, loadMoreView);
        }
        staggeredGridLayoutManager = new ExStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        staggeredGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), staggeredGridLayoutManager.getSpanCount()));

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }

    @Override
    public void onRefresh() {
        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
    }

    public class MyScrollListener extends OnRecyclerViewScrollListener {

        @Override
        public void onScrollUp() {

        }

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onBottom() {
            toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
        }

        @Override
        public void onMoved(int distanceX, int distanceY) {

        }
    }
}
